<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Box;
// use Encore\Admin\Widgets\Form;
use Encore\Admin\Form;

use App\Models\Account\RemainByNewUserLoginModel;
use App\ModelStatistic\PayRetainPlayer;
use App\ModelStatistic\StatisticCommon;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Admin\Extra\Search\Html;
use Illuminate\Support\Facades\Input;

use App\Models\Pay\Rate;
use App\Models\Pay\Recharge;
use App\Models\Area;

//用户统计
class PaystController extends Controller
{


    // 付费率
    public function anyRate(Request $request){

        $data = [];
        switch ($request->get('func')) {
            case 'chart':
                $data = $this->rateChart($request);
                $data['func'] = 'chart';
                $data['gfunc'] = 'data';
                $data['tpl'] = ['admin.charts.script', 'admin.charts.payrate'];
                $data['alias'] = '数据列表';
            break;

            default:
                $data = $this->rateData($request);
                $data['func'] = 'data';
                $data['gfunc'] = 'chart';
                $data['tpl'] = ['admin.payst.rate'];
                $data['alias'] = '图标统计';
        }

        
        return Admin::content(function (Content $content) use($data, $request){
		    $content->header('付费率');
		    $content->description('付费率，分为新增付费率 和 整体付费率');

            // 添加面包屑导航 since v1.5.7
            $content->breadcrumb(
                ['text' => '首页', 'url' => '/'],
                ['text' => '付费率', 'url' => '/admin/payst/rate']
            );

            $url_cur = url()->current();// . '?func='. $data['func'];

            $period_7 = \App\Service\Common::GetSomeDayPeriod(7, time());
            $param_7_day_arr_all = ["start" => \App\Service\Common::GTF($period_7[0], 0), 'end'=>0 ];
            $period_3 = \App\Service\Common::GetSomeDayPeriod(3, time());
            $param_3_day_arr_all = ["start" => \App\Service\Common::GTF($period_3[0], 0), 'end' => 0];
            // \Log::debug(__METHOD__, [$period_7, $param_7_day_search]);

            $param_1_day_arr = ['start' =>  \App\Service\Common::GTF(strtotime("0 day"), 0), "end" =>\App\Service\Common::GTF(strtotime("1 day"), 0) ];
            $param_2_day_arr = ['start' =>  \App\Service\Common::GTF(strtotime("-1 day"), 0), "end" =>\App\Service\Common::GTF(strtotime("0 day"), 0) ];
            $param_3_day_arr = ['start' =>  \App\Service\Common::GTF(strtotime("-2 day"), 0), "end" =>\App\Service\Common::GTF(strtotime("-1 day"), 0) ];
            $param_4_day_arr = ['start' =>  \App\Service\Common::GTF(strtotime("-3 day"), 0), "end" =>\App\Service\Common::GTF(strtotime("-2 day"), 0) ];
            $param_5_day_arr = ['start' =>  \App\Service\Common::GTF(strtotime("-4 day"), 0), "end" =>\App\Service\Common::GTF(strtotime("-3 day"), 0) ];

		    $content->row(Html::append([
                Html::button($data['alias'], '/admin/payst/rate?func='. $data['gfunc'] . $data['search_filter'],'btn-goto'),
                Html::dateInput('start', '开始日期', '', $request->get('start') ?:''),
                Html::dateInput('end', '结束日期', '', $request->get('end') ?:''),
                Html::button('GO', '/admin/payst/rate?func='.$data['func'], 'search-filter'),

                Html::button('Today', \App\Service\Common::build_url_query($url_cur,  $param_1_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 2', \App\Service\Common::build_url_query($url_cur,  $param_2_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 3', \App\Service\Common::build_url_query($url_cur,  $param_3_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 4', \App\Service\Common::build_url_query($url_cur,  $param_4_day_arr), 'btn-goto btn-warning'),
                Html::button('Day 5', \App\Service\Common::build_url_query($url_cur,  $param_5_day_arr), 'btn-goto btn-warning'),

                Html::button('1-3 Days ', \App\Service\Common::build_url_query($url_cur,  $param_3_day_arr_all), 'btn-goto btn-primary'),
                Html::button('1-7 Days ', \App\Service\Common::build_url_query($url_cur,  $param_7_day_arr_all), 'btn-goto btn-primary'),
                Html::sjs('/admin/payst/rate?func='. $data['func']),
                ]));	


            foreach ($data['tpl'] as $tpl) {
                $content->row(view($tpl, $data));
            }
        });

    }

    // 付费率 图形
    public function rateChart(Request $request){
        $start = $request->get('start');
        $end = $request->get('end');

        $model = new \App\Models\Pay\Rate;

        $res = $model->getAllRateData($start, $end);

        $res['new']['total'] = $res['new']['total'] - $res['new']['pay'];
        $res['all']['total'] = $res['all']['total'] - $res['all']['pay'];

        $res['search_filter'] = "&start={$start}&end={$end}";
        return $res;
    }

    // 付费率 数据
    public function rateData(Request $request){
        $start = $request->get('start');
        $end = $request->get('end');

        $model = new \App\Models\Pay\Rate;
        $result = $model->getAllRateData($start, $end);

        return [
            'new' => $result['new'],
            'all' => $result['all'],
            'left' => $result['left'],
            'search_filter' => "&start={$start}&end={$end}",
        ];
    }

    public function anyAreaRate(){
        return Admin::content(function (Content $content) {
            $content->header('Area Pay Rate Record');
            $content->description('');

            $period_7 = \App\Service\Common::GetSomeDayPeriod(7, time());
            $param_7_day_search = "&start=" . \App\Service\Common::GTF($period_7[0]);
            $period_3 = \App\Service\Common::GetSomeDayPeriod(3, time());
            $param_3_day_search = "&start=" . \App\Service\Common::GTF($period_3[0]);
            // \Log::debug(__METHOD__, [$period_7, $param_7_day_search]);

            $time_2 = "?start=" . \App\Service\Common::GTF(strtotime('-1 day'))."&end=".\App\Service\Common::GTF(strtotime('-0 day'));
            $time_3 = "?start=" . \App\Service\Common::GTF(strtotime('-3 day'))."&end=".\App\Service\Common::GTF(strtotime('-1 day'));
            $time_4 = "?start=" . \App\Service\Common::GTF(strtotime('-3 day'))."&end=".\App\Service\Common::GTF(strtotime('-2 day'));
            $time_5 = "?start=" . \App\Service\Common::GTF(strtotime('-4 day'))."&end=".\App\Service\Common::GTF(strtotime('-3 day'));

		    $content->row(Html::append([
                Html::button($data['alias'], '/admin/payst/area-rate','btn-goto'),
                Html::dateInput('start', 'Start Time', '', Input::get('start') ?:''),
                Html::dateInput('end', 'End Time', '', Input::get('end') ?:''),
                Html::button('GO', '/admin/payst/area-rate', 'search-filter'),
                Html::button('1 day', '/admin/payst/area-rate', 'btn-goto btn-warning'),
                Html::button('2 day', '/admin/payst/area-rate'. $time_2, 'btn-goto btn-warning'),
                Html::button('3 day', '/admin/payst/area-rate'. $time_3, 'btn-goto btn-warning'),
                Html::button('4 day', '/admin/payst/area-rate'. $time_4, 'btn-goto btn-warning'),
                Html::button('5 day', '/admin/payst/area-rate'. $time_5, 'btn-goto btn-warning'),
                Html::button('1-3 day', '/admin/payst/area-rate?a=1'.$param_3_day_search , 'btn-goto btn-primary'),
                Html::button('1-7 day', '/admin/payst/area-rate?a=1:'.$param_7_day_search , 'btn-goto btn-primary'),
                Html::sjs('/admin/payst/area-rate?func='. $data['func']),
                ]));	

            $grid = Admin::grid(Rate::class, function(Grid $grid){
                //$grid->model()->where('deleted_at', 0);//

                $grid->disableActions();
                $grid->disableRowSelector();
                // 第一列显示id字段，并将这一列设置为可排序列
        
                // $grid->areaId('area id');
                $grid->model()->orderBy('id', 'DESC');
                $grid->column('name')->style('width:120px;word-break:break-all;');

                $grid->show_total_rate('Total Rate')->display(function () {
                    $html = $this->total_rate['rate'] . '(' . $this->total_rate['pay'] . '/' . $this->total_rate['total'] . ')';
                    $access = \App\Service\Common::build_url_query(url('admin/areaorder/list-all'), [
                        'cp_area'=>$this->areaId, 
                        'created_time' => ['start'=> Input::get('start'), 'end'=> Input::get('end')],
                        ]);
                    return '<a href="'.$access.'" style="color:#000;display:block;"> '.$html . '</a>';
                })->style('background:; line-height:35px;');               

                $grid->show_new_rate('New User Rate')->display(function () {
                    $new_html = $this->new_rate['rate'] . '  (' . $this->new_rate['pay'] . '/' . $this->new_rate['total'] . ')';
                    return $new_html;
                })->style('background:#fffbcf;');
                $grid->show_left_rate('Old User Rate')->display(function () {
                    $new_html = $this->left_rate['rate'] . '  (' . $this->left_rate['pay'] . '/' . $this->left_rate['total'] . ')';
                    return $new_html;
                })->style('background:#e5fdf4;');


                $grid->filter(function ($filter) {

                    $filter->like('name', 'area name')->placeholder('');
                    

                    //$filter->disableIdFilter();
                });

            });
        
            $content->row($grid->render());

        });       
    }

    public function anyRecharge()
    {
        return Admin::content(function (Content $content) {
            $content->header('Area Pay Rate Record');
            $content->description('');

            \Log::debug(__METHOD__ . ' request load json 1', [ $_FILES]);

            $grid_file = Admin::Form(Recharge::class, function(Form $form)use($data){
                //$one->area_list = explode(',', $one->area_list);

                // $form->file('recharge_json', 'Recharge Json Reload')->removable()->addElementClass('apk_upload')->options([
                //     'showPreview' => false,
                //     'allowedFileExtensions'=>['apk'],
                //     'showUpload'=>true,
                //     'uploadAsync' =>true,
                //     'uploadUrl' => '/admin/payst/recharge-json',
                //     'uploadExtraData' => [
                //         '_token'    => csrf_token(),
                //         '_method'   => 'POST',
                //     ],
                // ])->setWidth(5, 3);
                $form->textarea('recharge_json', 'load json');
                $form->select('coin_type', 'Coin Type')->options([
                    'dollar' => 'dollar',
                    'rmb'   => 'rmb',
                    'deal'   => 'deal',
                ]);
                $form->disablePjax();
                $form->setAction('/admin/payst/recharge-json');

            });
            $content->row($grid_file);

            $grid = Admin::grid(Recharge::class, function(Grid $grid){
                //$grid->model()->where('deleted_at', 0);//

                // $grid->disableActions();
                $grid->disableRowSelector();
                // 第一列显示id字段，并将这一列设置为可排序列
        
                // $grid->areaId('area id');
                $grid->model()->orderBy('id', 'DESC');
                $grid->column('name')->editable()->style('width:120px;word-break:break-all;');
                $grid->recharge_id('recharge_id')->display(function($value) {
                    return $value;
                });

                $grid->dollar('dollar')->editable()->display(function ($value) {
                    return '$' . $value;
                });

                $grid->rmb('rmb')->editable()->display(function ($value) {
                    return '￥'. $value;
                });
                $grid->deal('RealPay')->editable()->display(function ($value) {
                    return ''. $value;
                });

                $grid->filter(function ($filter) {

                    $filter->like('name', 'area name')->placeholder('');
                    

                    //$filter->disableIdFilter();
                });
                $grid->actions(function($actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                });

            });
        
            $content->row($grid->render());

        });         
    }

    public function anyRechargeJson(Request $request){
        
        $json = $request->get('recharge_json');
        $type = $request->get('coin_type', 'dollar');
        $json = json_decode($json, true);
        Recharge::loadJson($json, $type);
    }

    public function anyChargeByRole() {
        return Admin::content(function (Content $content) use($data){
            $area_id = Input::get('cp_area') ?: Input::get('area');
            $area_all = \App\Models\Area::areaSelectData(0);
            
		    $content->header( " Group Recharge By Role  [{$area_all[$area_id]}]");
		    $content->description('Group Recharge By Role');

            // 添加面包屑导航 since v1.5.7
            $content->breadcrumb(
                ['text' => '首页', 'url' => '/'],
                ['text' => '存留', 'url' => '/admin/userst/remain']
            );

            $qd['cond']['start'] = $start = Input::get('start');
            $qd['cond']['end'] = $end = Input::get('end');
            $req_all = Input::all();

            $append_button = StatisticCommon::RetainHomeButton($area_id, 'day');
            array_unshift($append_button, Input::get('current', 1)==0 ? Html::button('current', \App\Service\Common::build_url_query(url()->current(), array_merge($req_all, ['current'=>1])), 'btn btn-goto btn-warning')
                :Html::button('current', \App\Service\Common::build_url_query(url()->current(), array_merge($req_all, ['current'=>0])), 'btn btn-goto btn-default') );

            array_unshift($append_button, Html::button('Generator', \App\Service\Common::build_url_query('/admin/payst/gen-charge-retain-role', $req_all),'btn-goto-ajax'));
            array_unshift($append_button, Html::button('RetainST', \App\Service\Common::build_url_query('/admin/userst/remain', $req_all), 'btn btn-goto btn-info'));

            $append_button[] = Input::get('day10', 0)==0 ? Html::button('10-20Day', \App\Service\Common::build_url_query(url()->current(), array_merge($req_all, ['day10'=>1])), 'btn btn-goto btn-info')
                :Html::button('10-20Day', \App\Service\Common::build_url_query(url()->current(), array_merge($req_all, ['day10'=>0])), 'btn btn-goto btn-default');

            $append_button[] = Input::get('day30', 0) ==0 ? Html::button('20-30Day', \App\Service\Common::build_url_query(url()->current(), array_merge($req_all, ['day30'=>1])), 'btn btn-goto btn-info')
                :Html::button('20-30Day', \App\Service\Common::build_url_query(url()->current(), array_merge($req_all, ['day30'=>0])), 'btn btn-goto btn-default');
		    $content->row(Html::append($append_button));		

			$grid = Admin::grid(PayRetainPlayer::class, function(Grid $grid) use($qd, $req_all){
                $colsour_func = function($show){
                    return $show ?:'';
                };
            
                //$grid->paginate(15);
			    // $grid->id('id');
			    $grid->reg_date('date')->style('border:1px solid #ccc;padding:10;')->display(function($value){
                    if (intval($value) == 0) {
                        return $value;
                    }
                    return '<div style="width:80px;">'.date("Y-m-d", $value). '</div>';
                });
			    $grid->reg_num('RegisterNum')->style('border:1px solid #ccc;padding:10;')->display(function($value){
                    return $value;
                });
                $grid->total_amount('TotalAmount')->style('border:1px solid #ccc;padding:10;')->display(function($value){
                    return $value;
                });
                $grid->avg_amount('AvgAmount')->style('border:1px solid #ccc;padding:10;')->display(function($value){
                    return $value;
                });

                $persent = true;
                for($i=1; $i<=30; $i++) {
                    $fld = 'day'.$i;
                    $ii = $i;
                    if (!$req_all['day10'] && $i > 10 && $i <=20){
                        continue;
                    }
                    if (!$req_all['day30'] && $i > 20 && $i <= 30){
                        continue;
                    }
			        $grid->$fld("Day-{$ii}")->style('border:1px solid #ccc;padding:10;text-align:left;')->display($colsour_func);
                }
			    // $grid->day7('week')->display($colsour_func);
			    // //$grid->week2('第二周');
			    // $grid->day14('half month')->display($colsour_func);
			    // $grid->day30('month')->display($colsour_func);

			    $grid->filter(function ($filter) {


			        // 设置created_at字段的范围查询
			        $filter->between('reg_date', '日期')->datetime();
                    $filter->equal('area')->select(\App\Models\Area::areaSelectData(1));
                    //
                    // $filter->execute();
                    // $filter->conditions();
                    $filter->where = $this->model;
                    $filter->disableIdFilter();
			    });

                $grid->actions(function($actions){
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->append('<a href="'.url('#'). $actions->row->account .'"><i class="glyphicon glyphicon-eye-open"></i></a>');
                });
                $grid->disableCreateButton();
                //$grid->disableExport();
                $grid->disableActions();
                $grid->disableRowSelector();
			});
       
		    $content->row($grid->render());	


        });       
    }

    public function genChargeRetainRole()
    {
        $gen = new PayRetainPlayer;
        $gen->generate();
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('generate success','success'), 'data' =>$one->delete_at]);
    }

    public function anyRechargeSave()
    {
            
        $id = Input::get('pk', 0);
        $fld = Input::get('name');
        $value = Input::get('value', '');
        \Log::debug("[CHARGE_PRICE][FIELD_SAVE]ID[${id}]FLD[$fld]VALUE[$value]", []);
        if (!$id) {
            echo json_encode(['code' => -444 ,'status'=>true, 'msg' => admin_toastr('pk id empty','error'), 'data' =>$one->delete_at]);
            return ;
        }
        $ret = Recharge::saveData([
            'id' => $id,
            $fld => $value,
        ], 'id');
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('fix price','success'), 'data' =>$one->delete_at]);
    }
}

